/*
 * @Author: huangyingli
 * @Date: 2023-02-24 13:28:50
 * @LastEditors: huangyingli
 * @LastEditTime: 2023-02-25 19:39:48
 * @Description:
 */
import { Button, Table, Modal, Form } from 'antd';
import { useEffect, useState } from 'react';
import AsyncForm from '../AsyncForm';

export default function CList(props) {
  const columns = props.form.children.map((c) => {
    return {
      title: c.form.label,
      key: c.form.key,
      dataIndex: c.form.key,
    };
  });

  const [list, setList] = useState(props.value || []);

  const [open, setOpen] = useState(false);

  function add() {
    setOpen(true);
  }

  useEffect(() => {
    setList(props.value)
  }, [props.value])

  function onFinish(values) {
    console.log('动态组件数据', values, list);
    let data = [...(list|| []), { key: Date.now(), ...values }];
    console.log('data', data);
    setList(data);

    props?.onChange(data);
  }

  return (
    <>
      <Button type='primary' onClick={add}>
        新增
      </Button>

      <Table columns={columns} dataSource={list}></Table>

      <Modal
        centered
        title='新增'
        open={open}
        onOk={() => setOpen(false)}
        onCancel={() => setOpen(false)}
      >
        <AsyncForm config={props.form.children} onFinish={onFinish}></AsyncForm>
      </Modal>
    </>
  );
}
